package org.ewancle.springboothivehdfs.util;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.util.Properties;

@Slf4j
public class ConnectionPoolUtil {

    /**
     * 创建HikariCP连接池数据源
     * @param driverClassName 驱动类名
     * @param jdbcUrl JDBC URL
     * @param properties 连接属性
     * @param poolSize 连接池大小
     * @return 数据源
     */
    public static DataSource createHikariDataSource(String driverClassName, String jdbcUrl,
                                                    Properties properties, int poolSize) {
        HikariConfig config = new HikariConfig();
        config.setDriverClassName(driverClassName);
        config.setJdbcUrl(jdbcUrl);

        // 设置连接属性
        if (properties != null) {
            config.setDataSourceProperties(properties);
        }

        // 配置连接池
        config.setMaximumPoolSize(poolSize);
        config.setMinimumIdle(2);
        config.setIdleTimeout(30000);
        config.setConnectionTimeout(30000);
        config.setMaxLifetime(1800000);
        config.setAutoCommit(true);
        config.setPoolName("HiveHikariCP");

        // 连接测试
        config.setConnectionTestQuery("SELECT 1");

        log.info("Creating HikariCP connection pool for JDBC URL: {}", jdbcUrl);
        return new HikariDataSource(config);
    }
}

